<?php

namespace app\api\controller;

use app\api\model\Order;
use app\common\controller\Api;
use fast\Http;
use think\Db;
use think\Log;
use app\api\model\Deal as DealModel;

/**
 * 定时任务接口
 */
class Cron extends Api
{

    protected $noNeedLogin = ['mill_pro','deal_order','lists'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 入口文件
     */
    public function lists()
    {
        $time = time();
        if ($time >= strtotime(date('23:00')))
        {
            $mill_pro = 'http://47.97.116.176/api/cron/mill_pro';
            Http::get($mill_pro);
            Http::get($mill_pro);
            Http::get($mill_pro);
            Http::get($mill_pro);
        }

        Http::get('http://47.97.116.176/api/cron/deal_order');

    }

    /**
     * 矿机生产
     */
    public function mill_pro()
    {

        $time = time();
        $today_time = strtotime(date('Y-m-d')); //  今天0点时间戳
        $tom_time = $today_time + 86400;  //  明天时间戳

        //  每天分红时间
        if ($time < strtotime(date('23:30')))
        {
            $this->error('分红时间没到');
        }

        //  先查询出来需要返币的用户矿机列表
        $mill_where = [
            'status' => ['=',config('MillStatus.enable')],
            'last_time'     =>  ['<' ,  $today_time],
        ];

        $mill_list = Db::name('user_mill')
            ->where($mill_where)
            ->limit(0,10)
            ->order('buy_time','desc')
            ->select();

        if (!$mill_list)
        {
            $this->success('所有矿机返币完成');
        }

        //
        $us = new \app\api\model\User();

        //  遍历每条数据
        foreach ($mill_list as $mill)
        {
            $uid        = intval($mill['user_id']);
            /*$period_sec = $mill['end_time'] - $mill['start_time'];              //  总运行秒数
            $period     = intval($period_sec / 86400);                      //  运行周期/天数*/
            $period     = $mill['total_days'];                              //  运行周期/天数
            $per_earn   = $mill['earnings'] / $period;                          //  每天应获取收益（钱）
            $sac_price  = $this->get_sac_price();                               //  获取sac价格
            $sac   = round($per_earn / $sac_price,4);         //  每天应返SAC数


            //  矿机列表数据
            $mill_update_data = [
                'last_time'     =>  $time,
                'earnings_yet'  =>  $mill['earnings_yet'] + $per_earn,
                'sac'           =>  $mill['sac'] + $sac,
                'period'        =>  $mill['period'] + 1,
            ];
            if ($mill['period'] + 1 >= $mill['total_days'])
            {
                //  如果今天是最后一次返币
                $mill_update_data['status'] = config('MillStatus.close');
            }


            //  用户资金记录表数据

            $user = $us->where('id','=',$uid)->find();
            if (!$user)
            {
                Log::error('矿机对应用户不存在：'.json_encode($mill));
                continue;

            }

            //  用户数据
            $user->sac += $sac;
            //  事务提交
            Db::startTrans();
            try{
                $millname = Db::name('mill')->where('id','=',$mill['id'])->find()['mill_name'];
                $this->get_divide($user,$sac);
                account_log($uid,0,$user->cny + $user->freeze_sac,$sac,$user->sac+$user->freeze_sac,"用户ID ".$uid. $millname." 产sac ". $sac. " 个");
                $user->save();
                Db::name('user_mill')->where('id','=',$mill['id'])->update($mill_update_data);
                Db::commit();
            }
            catch (\Exception $e)
            {
                Db::rollback();
                Log::error('矿机产币事务出错了：'.$e);
            }
        }
        //  写入日志完成提交
        $result = ['mill_list' => $mill_list,'time' => '矿机产币时间：'.date('Y-m-d H:i:s',$time)];
        trace(json_encode($result),'cron');
        $this->success($result);
    }


    //  获取分成
    private function get_divide($user,$sac)
    {
        $us = new \app\common\model\User();
        $first = config('site.first_profits_reward') / 100;
        $sec = config('site.second_profits_reward') / 100;
        $third = config('site.third_profits_reward') / 100;
        $first_num = config('site.first_profits_neednum');
        $sec_num = config('site.second_profits_neednum');
        $third_num = config('site.third_profits_neednum');

        if ($user->first && $us->where(['first' => $user->first])->count() >= $first_num)
        {
            $divide = $sac * $first;
            $sup = \app\common\model\User::get($user->first);
            if ($sup)
            {
                $sup->save(['sac' => $sup->sac + $divide]);
                account_log($sup->id,0,$sup->cny + $sup->freeze_cny,$divide,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 矿机产币分成','','','',2);
            }
        }

        if ($user->second && $us->where(['first' => $user->second])->count() >= $sec_num)
        {
            $divide = $sac * $sec;
            $sup = \app\common\model\User::get($user->second);
            if ($sup)
            {
                $sup->save(['sac' => $sup->sac + $divide]);
                account_log($sup->id,0,$sup->cny + $sup->freeze_cny,$divide,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 矿机产币分成','','','',2);
            }
        }

        if ($user->third && $us->where(['first' => $user->third])->count() >= $third_num)
        {
            $divide = $sac * $third;
            $sup = \app\common\model\User::get($user->third);
            if ($sup)
            {
                $sup->save(['sac' => $sup->sac + $divide]);
                account_log($sup->id,0,$sup->cny + $sup->freeze_cny,$divide,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 矿机产币分成','','','',2);
            }
        }

    }

    private function get_sac_price()
    {
        $data = Http::get(config('sac_url'));
        $data = json_decode($data, true);
        $price = end($data['price_usd'])[1];        //比特币
        $rate = config('site.rate');
        $sacprice = $price * $rate;
        return $sacprice;
    }



    //处理封号和付币的状态
    public function deal_order()
    {
        $time = time() - 12*3600;
        $orderModel = new Order();
        $userModel = new \app\admin\model\User();
        $dealModel = new \app\admin\model\Deal();
        $where = [
            'status' => ['in','1,2'],
            'create_time' => ['<',$time]
        ];
        $orders = $orderModel           //查询出所有超过24小时的撮合订单
            ->where($where)
            ->select();
//        $this->success('',$orders);exit;
        foreach($orders as $value)
        {
            if($value->status == '1'){      //如果是未付款的订单
//                $this->success('',$value);exit;
                Db::startTrans();
                try{
                    $userModel->save(['status'=>'hidden'],['id'=>$value->buy_user_id]); //直接冻结用户
                    $sale_deal = $dealModel->where('deal_sn',$value->sale_deal_sn)->find(); //查询出来卖家交易的cny
                    $sale_deal->residue_cny += $value->cny;                             //把cny返给挂单继续交易
                    $sale_deal->status = 1;                                             //交易表状态改为未匹配
                    $sale_deal->match_time = 0;                                         //匹配时间改为0
                    $sale_deal->create_time = time();
                    $sale_deal->save();
                    $buy_deal = $dealModel->where('deal_sn',$value->buy_deal_sn)->find();
                    $buy_deal->status = 0;
                    $buy_deal->save();
                    $orderModel->where('sale_deal_sn',$value->sale_deal_sn)->delete();      //删除订单表
                    Db::commit();
                }
                catch (\Exception $e)
                {
                    Db::rollback();
                    Log::error('未付款封号出错了：'.$e);
                }
            }
            if($value->status == '2')   //如果是未付币的订单
            {
//                $this->success('',$value);exit;
                Db::startTrans();               //模拟确认付币
                try{
                    $order_info = $value;
                    $user = \app\admin\model\User::get($order_info->sale_user_id);
                    $buy_user =  \app\admin\model\User::get($order_info->buy_user_id);

                    $buy_user_update = [
                        'cny'       =>  $buy_user->cny + $order_info->cny,
                        'total_cny' =>  $buy_user->total_cny + $order_info->cny
                    ];
                    $order_info->save(['status' => config('OrderStatus.Finished'),'complete_time' => time()]);    //  更新当笔交易状态
                    $user->save(['freeze_cny' => $user->freeze_cny - $order_info->cny]);    //  更新卖家币数
                    $buy_user->save($buy_user_update);  //  更新买家币数
                    //  记录资金流动
                    account_log($user->id,'',$user->cny + $user->freeze_cny,0,$user->sac,'卖家ID'.$user->id.'确认付币'.$order_info->cny,$order_info->cny * -1,$order_info->sale_deal_sn);
                    account_log($buy_user->id,$order_info->cny,$buy_user->cny + $buy_user->freeze_cny,0,$buy_user->sac,'买家ID'.$buy_user->id.'收币'.$order_info->cny,'',$order_info->buy_deal_sn);
                    //  判断是否修改交易标状态
                    $deal_finish_status = ['status' => config('DealStatus.Finished'),'complate_time' => time()];

                    //  查找是否还有未完成记录
                    $buy_finished = $orderModel->where([
                        'buy_deal_sn' => $order_info->buy_deal_sn,
                        'status' => ['<>', config('OrderStatus.Finished')]
                    ])->find();
                    $sale_finished = $orderModel->where([
                        'sale_deal_sn'  =>  $order_info->sale_deal_sn,
                        'status'    =>  ['<>' , config('OrderStatus.Finished')]
                    ])->find();
                    if (empty($buy_finished))
                    {
                        $deal_info = DealModel::get(['deal_sn' => $order_info->buy_deal_sn]);
                        if($deal_info && $deal_info->residue_cny <= 0){
                            $deal_info->save($deal_finish_status);
                        }
                    }
                    if (empty($sale_finished))
                    {
                        $deal_info = DealModel::get(['deal_sn' => $order_info->sale_deal_sn]);
                        if($deal_info && $deal_info->residue_cny <= 0){
                            $deal_info->save($deal_finish_status);
                        }
                    }
                    //  确认付币给买家发送短信
                    send_common_sms($buy_user->mobile,$order_info->order_sn,'已成功交易');
                    send_common_sms($user->mobile,$order_info->order_sn,'已成功交易');   //  卖家点确认卖家发送信息
                    Db::commit();
                }
                catch (\Exception $e)
                {
                    Db::rollback();
                    Log::error('到时间确认付币出错了：'.$e);
                }
            }
        }
        $result = ['orders'=>$orders,'time'=>'封号和付币'.date('Y-m-d H:i:s',$time)];
        trace($result,'deal_order');
        $this->success($result);
    }
}

